<?php

namespace App\Http\Controllers;

use App\Constants\ResponseArray;
use App\Http\Services\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends BaseController
{

    public function uploadImage(Request $request)
    {

        $data = $request->all();
        $rules = [
            'file' => 'required|file',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }

        return UploadService::uploadImage($request);
    }

    /**
     * 获取指定图片访问url
     * @param Request $request
     * @return array
     */
    public function getImageUrl(Request $request)
    {
        $data = $request->all();
        $rules = [
            'path' => 'required|string',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }
        // 获得指定文件的网址
        $disk = Storage::disk('oss');

        $url = $disk->getAdapter()->getTemporaryUrl($data['path'], 3000, ['x-oss-process' => 'image/circle,r_100']);

        if (!$url)
        {
            return ResponseArray::abortMessage('Get Image Url Failed.');
        }

        return ResponseArray::response($url,'Get Image Url Successfully.');

        // 获取文件访问地址「公共读的 bucket 才生效」
        //$url = $disk->getAdapter()->getUrl('folder/my_file.txt');

        // 设置文件访问有效期「$timeout 为多少秒过期」「私有 bucket 才可看见效果」
        //$url = $disk->getAdapter()->getTemporaryUrl('cat.png', $timeout, ['x-oss-process' => 'image/circle,r_100']);

        // 可切换其他 bucket「需要在 config 配置文件中配置 buckets」
        //$exists = $disk->getAdapter()->bucket('test')->xxx('file.jpg');
    }

}
